<template>
  <div class="salary-management">
    <!-- 页面头部 -->
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-800">薪资管理</h1>
      <div class="flex gap-2">
        <el-button type="primary" @click="handleCalculateSalary">
          <el-icon><Calculator /></el-icon>
          计算工资
        </el-button>
        <el-button type="success" @click="handleBatchPay">
          <el-icon><Money /></el-icon>
          批量发放
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-blue-100 text-blue-600">
            <el-icon size="24"><Money /></el-icon>
          </div>
          <div class="ml-4">
            <div class="text-2xl font-bold text-gray-800">¥{{ stats.totalSalary.toLocaleString() }}</div>
            <div class="text-sm text-gray-500">本月总薪资</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-green-100 text-green-600">
            <el-icon size="24"><Check /></el-icon>
          </div>
          <div class="ml-4">
            <div class="text-2xl font-bold text-gray-800">{{ stats.paidCount }}</div>
            <div class="text-sm text-gray-500">已发放人数</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-yellow-100 text-yellow-600">
            <el-icon size="24"><Clock /></el-icon>
          </div>
          <div class="ml-4">
            <div class="text-2xl font-bold text-gray-800">{{ stats.pendingCount }}</div>
            <div class="text-sm text-gray-500">待发放人数</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-red-100 text-red-600">
            <el-icon size="24"><Warning /></el-icon>
          </div>
          <div class="ml-4">
            <div class="text-2xl font-bold text-gray-800">¥{{ stats.totalTax.toLocaleString() }}</div>
            <div class="text-sm text-gray-500">本月个税</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 搜索表单 -->
    <el-card class="mb-6">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="员工姓名">
          <el-input
            v-model="searchForm.employeeName"
            placeholder="请输入员工姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="部门">
          <el-select
            v-model="searchForm.department"
            placeholder="请选择部门"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="技术部" value="技术部" />
            <el-option label="销售部" value="销售部" />
            <el-option label="人事部" value="人事部" />
            <el-option label="财务部" value="财务部" />
          </el-select>
        </el-form-item>
        <el-form-item label="发放状态">
          <el-select
            v-model="searchForm.payStatus"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="已发放" value="已发放" />
            <el-option label="待发放" value="待发放" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item label="薪资月份">
          <el-date-picker
            v-model="searchForm.salaryMonth"
            type="month"
            placeholder="选择月份"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 薪资列表表格 -->
    <el-card>
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold">薪资列表</h3>
        <div class="flex gap-2">
          <el-button type="warning" @click="exportSalary">
            <el-icon><Download /></el-icon>
            导出薪资
          </el-button>
          <el-button type="info" @click="showSalaryReport">
            <el-icon><DataAnalysis /></el-icon>
            薪资报表
          </el-button>
        </div>
      </div>
      
      <el-table
        :data="salaryList"
        style="width: 100%"
        v-loading="loading"
        stripe
        border
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="employeeName" label="员工姓名" width="100" />
        <el-table-column prop="employeeNo" label="工号" width="120" />
        <el-table-column prop="department" label="部门" width="100" />
        <el-table-column prop="position" label="职位" width="100" />
        <el-table-column prop="baseSalary" label="基本工资" width="120">
          <template #default="{ row }">
            <span class="text-blue-600 font-medium">¥{{ row.baseSalary.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="allowance" label="津贴补助" width="120">
          <template #default="{ row }">
            <span class="text-green-600 font-medium">¥{{ row.allowance.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="overtimePay" label="加班费" width="100">
          <template #default="{ row }">
            <span class="text-orange-600 font-medium">¥{{ row.overtimePay.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="deduction" label="扣款" width="100">
          <template #default="{ row }">
            <span class="text-red-600 font-medium">¥{{ row.deduction.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="socialInsurance" label="社保" width="100">
          <template #default="{ row }">
            <span class="text-gray-600 font-medium">¥{{ row.socialInsurance.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="tax" label="个税" width="100">
          <template #default="{ row }">
            <span class="text-purple-600 font-medium">¥{{ row.tax.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="netSalary" label="实发工资" width="120">
          <template #default="{ row }">
            <span class="text-green-700 font-bold text-lg">¥{{ row.netSalary.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="payStatus" label="发放状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getPayStatusType(row.payStatus)"
              size="small"
            >
              {{ row.payStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payDate" label="发放日期" width="120" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleViewDetail(row)"
              link
            >
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleEdit(row)"
              link
              v-if="row.payStatus === '待发放'"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="handlePay(row)"
              link
              v-if="row.payStatus === '待发放'"
            >
              <el-icon><Money /></el-icon>
              发放
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-center mt-6">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 薪资详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="薪资详情"
      width="600px"
    >
      <div v-if="currentSalary" class="salary-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="员工姓名">{{ currentSalary.employeeName }}</el-descriptions-item>
          <el-descriptions-item label="工号">{{ currentSalary.employeeNo }}</el-descriptions-item>
          <el-descriptions-item label="部门">{{ currentSalary.department }}</el-descriptions-item>
          <el-descriptions-item label="职位">{{ currentSalary.position }}</el-descriptions-item>
          <el-descriptions-item label="薪资月份">{{ currentSalary.salaryMonth }}</el-descriptions-item>
          <el-descriptions-item label="出勤天数">{{ currentSalary.workDays }}天</el-descriptions-item>
        </el-descriptions>
        
        <div class="mt-4">
          <h4 class="text-lg font-semibold mb-3">薪资构成</h4>
          <el-table :data="salaryBreakdown" border>
            <el-table-column prop="item" label="项目" width="150" />
            <el-table-column prop="amount" label="金额" align="right">
              <template #default="{ row }">
                <span :class="row.type === 'deduction' ? 'text-red-600' : 'text-green-600'">
                  {{ row.type === 'deduction' ? '-' : '+' }}¥{{ Math.abs(row.amount).toLocaleString() }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑薪资对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑薪资"
      width="500px"
    >
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="100px">
        <el-form-item label="基本工资" prop="baseSalary">
          <el-input-number
            v-model="editForm.baseSalary"
            :min="0"
            :max="999999"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="津贴补助" prop="allowance">
          <el-input-number
            v-model="editForm.allowance"
            :min="0"
            :max="99999"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="加班费" prop="overtimePay">
          <el-input-number
            v-model="editForm.overtimePay"
            :min="0"
            :max="99999"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="扣款" prop="deduction">
          <el-input-number
            v-model="editForm.deduction"
            :min="0"
            :max="99999"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="editForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 薪资报表对话框 -->
    <el-dialog
      v-model="reportDialogVisible"
      title="薪资报表"
      width="800px"
    >
      <div class="salary-report">
        <div class="grid grid-cols-2 gap-4 mb-6">
          <el-card>
            <div class="text-center">
              <div class="text-2xl font-bold text-blue-600">¥{{ reportData.totalAmount.toLocaleString() }}</div>
              <div class="text-sm text-gray-500">总薪资支出</div>
            </div>
          </el-card>
          <el-card>
            <div class="text-center">
              <div class="text-2xl font-bold text-green-600">¥{{ reportData.avgSalary.toLocaleString() }}</div>
              <div class="text-sm text-gray-500">平均薪资</div>
            </div>
          </el-card>
        </div>
        
        <div class="mb-4">
          <h4 class="text-lg font-semibold mb-3">部门薪资统计</h4>
          <el-table :data="reportData.departmentStats" border>
            <el-table-column prop="department" label="部门" />
            <el-table-column prop="employeeCount" label="人数" align="center" />
            <el-table-column prop="totalSalary" label="总薪资" align="right">
              <template #default="{ row }">
                ¥{{ row.totalSalary.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="avgSalary" label="平均薪资" align="right">
              <template #default="{ row }">
                ¥{{ row.avgSalary.toLocaleString() }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Money,
  Check,
  Clock,
  Warning,
  Search,
  Refresh,
  Download,
  DataAnalysis,
  View,
  Edit
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)
const editDialogVisible = ref(false)
const reportDialogVisible = ref(false)
const editFormRef = ref()
const currentSalary = ref(null)

// 统计数据
const stats = reactive({
  totalSalary: 1250000,
  paidCount: 120,
  pendingCount: 36,
  totalTax: 125000
})

// 搜索表单
const searchForm = reactive({
  employeeName: '',
  department: '',
  payStatus: '',
  salaryMonth: ''
})

// 编辑表单
const editForm = reactive({
  id: null,
  baseSalary: 0,
  allowance: 0,
  overtimePay: 0,
  deduction: 0,
  remark: ''
})

// 编辑表单验证规则
const editRules = {
  baseSalary: [
    { required: true, message: '请输入基本工资', trigger: 'blur' },
    { type: 'number', min: 0, message: '基本工资不能为负数', trigger: 'blur' }
  ]
}

// 薪资列表
const salaryList = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 薪资明细
const salaryBreakdown = computed(() => {
  if (!currentSalary.value) return []
  
  return [
    { item: '基本工资', amount: currentSalary.value.baseSalary, type: 'income', remark: '月度基本工资' },
    { item: '津贴补助', amount: currentSalary.value.allowance, type: 'income', remark: '各类津贴' },
    { item: '加班费', amount: currentSalary.value.overtimePay, type: 'income', remark: '加班工资' },
    { item: '社会保险', amount: -currentSalary.value.socialInsurance, type: 'deduction', remark: '个人承担部分' },
    { item: '个人所得税', amount: -currentSalary.value.tax, type: 'deduction', remark: '代扣代缴' },
    { item: '其他扣款', amount: -currentSalary.value.deduction, type: 'deduction', remark: '迟到、早退等' }
  ]
})

// 报表数据
const reportData = reactive({
  totalAmount: 1250000,
  avgSalary: 8012,
  departmentStats: [
    { department: '技术部', employeeCount: 45, totalSalary: 675000, avgSalary: 15000 },
    { department: '销售部', employeeCount: 32, totalSalary: 384000, avgSalary: 12000 },
    { department: '人事部', employeeCount: 8, totalSalary: 64000, avgSalary: 8000 },
    { department: '财务部', employeeCount: 12, totalSalary: 108000, avgSalary: 9000 },
    { department: '市场部', employeeCount: 15, totalSalary: 165000, avgSalary: 11000 }
  ]
})

// 获取发放状态类型
const getPayStatusType = (status) => {
  const statusMap = {
    '已发放': 'success',
    '待发放': 'warning',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取薪资列表
const getSalaryList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    const mockData = [
      {
        id: 1,
        employeeName: '张三',
        employeeNo: 'EMP001',
        department: '技术部',
        position: '高级工程师',
        salaryMonth: '2024-01',
        workDays: 22,
        baseSalary: 15000,
        allowance: 2000,
        overtimePay: 1500,
        deduction: 200,
        socialInsurance: 1800,
        tax: 1650,
        netSalary: 14850,
        payStatus: '已发放',
        payDate: '2024-01-25'
      },
      {
        id: 2,
        employeeName: '李四',
        employeeNo: 'EMP002',
        department: '销售部',
        position: '销售经理',
        salaryMonth: '2024-01',
        workDays: 21,
        baseSalary: 12000,
        allowance: 1500,
        overtimePay: 800,
        deduction: 0,
        socialInsurance: 1440,
        tax: 1286,
        netSalary: 11574,
        payStatus: '已发放',
        payDate: '2024-01-25'
      },
      {
        id: 3,
        employeeName: '王五',
        employeeNo: 'EMP003',
        department: '人事部',
        position: '人事专员',
        salaryMonth: '2024-01',
        workDays: 22,
        baseSalary: 8000,
        allowance: 800,
        overtimePay: 400,
        deduction: 100,
        socialInsurance: 960,
        tax: 814,
        netSalary: 7326,
        payStatus: '待发放',
        payDate: ''
      },
      {
        id: 4,
        employeeName: '赵六',
        employeeNo: 'EMP004',
        department: '财务部',
        position: '会计',
        salaryMonth: '2024-01',
        workDays: 20,
        baseSalary: 9000,
        allowance: 1000,
        overtimePay: 600,
        deduction: 300,
        socialInsurance: 1080,
        tax: 922,
        netSalary: 8298,
        payStatus: '待发放',
        payDate: ''
      },
      {
        id: 5,
        employeeName: '孙七',
        employeeNo: 'EMP005',
        department: '市场部',
        position: '市场主管',
        salaryMonth: '2024-01',
        workDays: 22,
        baseSalary: 11000,
        allowance: 1200,
        overtimePay: 1000,
        deduction: 0,
        socialInsurance: 1320,
        tax: 1188,
        netSalary: 10692,
        payStatus: '已发放',
        payDate: '2024-01-25'
      }
    ]
    
    salaryList.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('获取薪资列表失败')
  } finally {
    loading.value = false
  }
}

// 表格合计行
const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (index === 1 || index === 2 || index === 3 || index === 4) {
      sums[index] = ''
      return
    }
    
    const values = data.map(item => Number(item[column.property]))
    if (!values.every(value => isNaN(value))) {
      const sum = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
      sums[index] = `¥${sum.toLocaleString()}`
    } else {
      sums[index] = ''
    }
  })
  return sums
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getSalaryList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    employeeName: '',
    department: '',
    payStatus: '',
    salaryMonth: ''
  })
  handleSearch()
}

// 计算工资
const handleCalculateSalary = () => {
  ElMessage.success('工资计算完成')
  getSalaryList()
}

// 批量发放
const handleBatchPay = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要批量发放薪资吗？',
      '批量发放确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('批量发放成功')
    getSalaryList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量发放失败')
    }
  }
}

// 查看详情
const handleViewDetail = (row) => {
  currentSalary.value = row
  detailDialogVisible.value = true
}

// 编辑薪资
const handleEdit = (row) => {
  Object.assign(editForm, {
    id: row.id,
    baseSalary: row.baseSalary,
    allowance: row.allowance,
    overtimePay: row.overtimePay,
    deduction: row.deduction,
    remark: ''
  })
  editDialogVisible.value = true
}

// 编辑提交
const handleEditSubmit = async () => {
  try {
    await editFormRef.value.validate()
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('薪资更新成功')
    editDialogVisible.value = false
    getSalaryList()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 发放薪资
const handlePay = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要发放 "${row.employeeName}" 的薪资吗？`,
      '发放确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('薪资发放成功')
    getSalaryList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('薪资发放失败')
    }
  }
}

// 导出薪资
const exportSalary = () => {
  ElMessage.success('薪资数据导出成功')
}

// 显示薪资报表
const showSalaryReport = () => {
  reportDialogVisible.value = true
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  getSalaryList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  getSalaryList()
}

// 组件挂载时获取数据
onMounted(() => {
  getSalaryList()
})
</script>

<style scoped>
.salary-management {
  padding: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.salary-detail .el-descriptions {
  margin-bottom: 20px;
}

.salary-report .el-card {
  border: 1px solid #e4e7ed;
}

.dialog-footer {
  text-align: right;
}
</style>